//
//  FighterMoveBezierTwoByAction.cpp
//  airfight
//
//  Created by aaron more on 12-11-6.
//  Copyright (c) 2012年 moonriver. All rights reserved.
//

#include <iostream>
#include "FighterMoveBezierTwoByAction.h"
#include "math.h"

static inline float bezierTwoTrack( float a, float b, float c, float t )
{
    return (powf(1-t,2) * a + 
            2*t*(1-t)*b + 
            powf(t,2)*c);
}

float getRotateAngle(CCPoint curpos, CCPoint newpos)
{
    float angle;
    float disX = newpos.x - curpos.x;
    float disY = newpos.y - curpos.y;
    float dis = sqrt(pow(disX, 2) + pow(disY, 2));
    if (dis > -0.000001 && dis < 0.000001 )
    {
        dis = 0.000001;
    }
    angle = acos(disY/dis);
    angle = disX > 0? angle : (2*PI - angle);
    angle = angle * 180 / PI;
    
    return angle;
}

FighterMoveBezierTwoByAction* FighterMoveBezierTwoByAction::create(Move* p_move)
{
    FighterMoveBezierTwoByAction *pBezierBy = new FighterMoveBezierTwoByAction();
    ccBezierConfig bezierConfig;
    CCArray* controls = p_move->getControls();
    bezierConfig.controlPoint_1 = ((Control*)controls->objectAtIndex(0))->getControlPoint();
    bezierConfig.endPosition = p_move->getEndPoint();
    pBezierBy->setMoveAngle(p_move->getAngle());
    pBezierBy->setAngleWish(p_move->getWish());
    pBezierBy->initWithDuration(p_move->getDuration(), bezierConfig);
    pBezierBy->autorelease();
    return pBezierBy;
}

void FighterMoveBezierTwoByAction::startWithTarget(CCNode *pTarget)
{
    CCActionInterval::startWithTarget(pTarget);
    m_startPosition = pTarget->getPosition();
}


bool FighterMoveBezierTwoByAction::initWithDuration(float duration, const ccBezierConfig& c)
{
    if (CCActionInterval::initWithDuration(duration))
    {
        m_sConfig = c;
        return true;
    }
    
    return false;
}

void FighterMoveBezierTwoByAction::update(float time)
{
    if (m_pTarget)
    {
        float xa = 0;
        float xb = m_sConfig.controlPoint_1.x;
        float xc = m_sConfig.endPosition.x;
        
        float ya = 0;
        float yb = m_sConfig.controlPoint_1.y;
        float yc = m_sConfig.endPosition.y;
        
        float x = bezierTwoTrack(xa, xb, xc, time);
        float y = bezierTwoTrack(ya, yb, yc, time);
        
        CCPoint newPos =  ccpAdd(m_startPosition, ccp(x, y));
        
        EnemyFighterSprite* enemySprite = (EnemyFighterSprite*)m_pTarget;
        if(this->getAngleWish() == 1){
            enemySprite->setRotation(this->getMoveAngle());
        }
        else
        {
            float rotation = getRotateAngle(enemySprite->getPosition(), newPos);
            enemySprite->setRotation(rotation);
        }
        enemySprite->setPosition(newPos);
    }
}
